<script scope setup>
import { User, Lock } from '@element-plus/icons-vue'

import {onMounted, ref} from 'vue'
import {ElMessage} from "element-plus";
import {useTokenSotre} from "@/stores/token.js";
const tokenStore = useTokenSotre()
//定义发送验证码显示判断值
const codeshow=ref(true);
const codeshow2=ref(true);
//根据规则按钮是否可用
function isSubmitDisabled(type) {
  if (type===1){
    return !registerData.value.userName || !registerData.value.password || !registerData.value.code;
  }else if(type===2){
    return !registerData.value.password || !registerData.value.code || !registerData.value.code===4;
  } else {
    return !registerData.value.userName || !registerData.value.password || !registerData.value.rePassword;
  }
}
function isSubmitDisabled2(){
  return !registerData.value.phoneNumber || registerData.value.phoneNumber.length!==11
}
//控制注册与登录表单的显示， 默认显示注册
const isRegister = ref(false)
//定义数据模型
const registerData=ref({
  userName:'',
  password:'',
  rePassword:'',
  phoneNumber:'',
  image:'',
  email:'',
  code1:'',
  code2:'',
  type :1
})
//校验密码的函数
const checkRePassword = (rule, value, callback) => {
  if(value===''){
    callback(new Error('请再次确认密码'))
  }else if(value !== registerData.value.password){
    callback(new Error('请确保两次密码输入相同'))
  }else {
    callback()
  }
}
// const setCategory = async ()=>{
//   let result = await GetService
//   console.log(result)
//   coupon.value = result.data
// }
const rules={
  username:[
    {required:true,message:'请输入用户名',trigger:'blur'},
    {min:1,max:16,message:'长度为1-16位非空字符',trigger:'blur'}
  ],
  password:[
    {required:true,message:'请输入密码',trigger:'blur'},
    {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  ],
  rePassword:[
    {validator:checkRePassword,trigger:'blur'}
  ],
  phoneNumber:[
      {required:true,message:'请输入手机号',trigger:'blur'},
      {min:11,max:11,message: '长度有误',trigger:'blur'}
  ],
  code:[{required:true,message:'请输入验证码',trigger:'blur'},{min:4,max:4,message: '长度有误',trigger:'blur'}]
}
import {emailService, userRegisterService} from "@/api/user";
import {useRouter} from 'vue-router'
const router = useRouter()
//调用后台接口，完成注册
const register = async ()=>{
  // if (registerData.value.code!==result1.data){
  //   ElMessage.error('验证码错误')
  //   return
  // }
  //registerData是一个响应式数据，如果需要获取值，需要 .value
  let result = await userRegisterService(registerData.value)
  ElMessage.success(result.msg?result.msg:'注册成功')
  tokenStore.setToken(result.data)
  router.push("/")
}

import {userLoginService} from "@/api/user";
//绑定数据，复用注册表单模型
//登录函数
const login = async ()=>{
  let result = await userLoginService(registerData.value)
  console.log(result.data)

  // if (registerData.value.code!==result1.data){
  //   ElMessage.error('验证码错误')
  //   return
  // }
  ElMessage.success(result.msg?result.msg:'登录成功')
  tokenStore.setToken(result.data)
  router.push("/")
}

//定义函数，清空数据模型的数据
const clearRegisterData=()=>{
  registerData.value={
    userName:'',
    password:'',
    rePassword:'',
    phoneService:'',
    type:'',
    email:''
  }
}

import {phoneService} from "@/api/user";

const number = async ()=>{
  await phoneService(registerData.value.phoneNumber,registerData.value.type)
  codeshow.value=false
  ElMessage.success('发送成功')
}

const a =ref(60)
const a2 =ref(60)
const clock=()=>
{
  codeshow.value=false
  let timer = setInterval(() => {
    a.value--
    if (a.value === 0) {
      clearInterval(timer)
      codeshow.value = true
      a.value=60
      return true
    }
  }, 1000)
}
const clock2=()=>
{
  codeshow2.value=false
  let timer = setInterval(() => {
    a2.value--
    if (a2.value === 0) {
      clearInterval(timer)
      codeshow2.value = true
      a2.value=60
      return true
    }
  }, 1000)
}
import {useBlackSotre} from '@/stores/black'
import emitter from "@/utils/buts";
const isDark = useBlackSotre()
const toggleDark = () =>{
  let element = document.getElementById('login');
  if (isDark.black===false){
    element.style.background = 'linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%)';
  }else {
    element.style.background = 'grey';
  }
}
emitter.on("login", () => {
  toggleDark()
});
onMounted(()=>{
  if (isDark.black==false){
    let element = document.getElementById('login');
    element.style.background = 'grey';
  }
})

const getEmail= async ()=>{
  registerData.value.type=0
  await emailService(registerData.value.email,registerData.value.type)
  ElMessage.success("已发送验证码到账号绑定的邮箱")
}
//上传成功的回调函数
const uploadSuccess=(result)=>{
  registerData.value.image = result.data
}
</script>

<template>
  <el-row class="login-page" id="login" >
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules" >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="userName">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.userName"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请再次输入密码" v-model="registerData.rePassword"></el-input>
        </el-form-item>
        <el-form-item label="请上传用户头像" >
          <el-upload  class="avatar-uploader" on-exceed="exceeds" :auto-upload="true" :show-file-list="false"  element-loading-text="正在上传" action="http://localhost:8080/upload"  name="file" :headers="{'Authorization':tokenStore.token.data}"
                     :on-success='uploadSuccess'>
            <img width="20px" height="20px" v-if="registerData.image" :src="registerData.image" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item prop="phoneNumber">
          <el-input v-model="registerData.phoneNumber" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input style="width:67%" v-model="registerData.code1" placeholder="请输入验证码"></el-input>
          <el-button style="margin-left: 15px" v-if="codeshow" :disabled="isSubmitDisabled2()" @click="number();clock()">获取验证码</el-button>
          <el-button style="margin-left: 67px" v-if="!codeshow" disabled="disabled">{{a}}</el-button>
        </el-form-item>
        <el-form-item >
          <el-input v-model="registerData.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input style="width:67%" v-model="registerData.code2" placeholder="请输入验证码"></el-input>
          <el-button style="margin-left: 15px" v-if="codeshow2"  @click="getEmail();clock2()">获取验证码</el-button>
          <el-button style="margin-left: 67px" v-if="!codeshow2" disabled="disabled">{{a2}}</el-button>
        </el-form-item>
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space :disabled="isSubmitDisabled(0)" @click="register">
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterData()" >
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <!-- 登录表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-else  :model="registerData" :rules="rules">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="phoneNumber">
          <el-input v-model="registerData.phoneNumber" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="code1">
          <el-input style="width:67% " v-model="registerData.code" placeholder="请输入验证码"></el-input>
          <el-button style="margin-left: 15px" v-if="codeshow" :disabled="isSubmitDisabled2()" @click="registerData.type=1;number();clock()">发送验证码</el-button>
          <el-button style="margin-left: 67px" v-if="!codeshow" >{{a}}</el-button>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" @click="getEmail" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space :disabled="isSubmitDisabled(2)" @click="login">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterData()" >
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 80vh;
  width: 99%;
  margin-top: 10px;
  margin-left: 8px;
  border-radius:10px;
  background: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%);
  border-right: 10px;
  .bg {
    background: url('@/assets/IMG_20240601_085558.jpg') no-repeat 60% center / 240px auto,
    url('@/assets/IMG_20240601_085714.jpg') no-repeat center / cover;
    border-radius: 10px;
    //width: 80%;
    height: 95%;
    margin: 20px 0  0 10px;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    //background-color: azure;
    //border-radius: 10px;
    .title {
      margin: 0 auto;
    }



    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
.el-alert {
  margin: 20px 0 0;
}
.el-alert:first-child {
  margin: 0;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>